package cn.jetpiece.cloud.common.app.modular.message.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.common.api.message.model.query.AnnouncementQuery;
import cn.jetpiece.cloud.common.api.message.model.result.AnnouncementMessageResult;
import cn.jetpiece.cloud.common.api.message.constans.MessageConstant;
import cn.jetpiece.cloud.common.app.modular.message.entity.Announcement;
import cn.jetpiece.cloud.common.app.modular.message.entity.AnnouncementSend;
import cn.jetpiece.cloud.common.app.modular.message.mapper.AnnouncementMapper;
import cn.jetpiece.cloud.common.app.modular.message.mapper.AnnouncementSendMapper;
import cn.jetpiece.cloud.common.app.modular.message.service.IAnnouncementService;
import cn.jetpiece.cloud.core.context.LoginUserContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统通告表
 *
 * @author jetpiece
 * @since 2022-11-16
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements IAnnouncementService {

    @Resource
    private AnnouncementSendMapper announcementSendMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAnnouncement(Announcement entity) {
        if (StrUtil.isBlank(entity.getSender())){
            entity.setSender(LoginUserContext.getInstance().getUsername());
        }
        boolean result = super.save(entity);
        if (result && entity.getMsgReceiverUserType().equals(MessageConstant.MSG_RECEIVER_USER_TYPE_USER)) {
            List<String> userIdList = StrUtil.split(entity.getUserIds(), ",");
            Date refDate = new Date();
            userIdList.forEach(userId -> {
                AnnouncementSend announcementSend = new AnnouncementSend();
                announcementSend.setAnnouncementId(entity.getId());
                announcementSend.setUserId(userId);
                announcementSend.setReadFlag(MessageConstant.NO_READ_FLAG);
                announcementSend.setReadTime(refDate);
                announcementSendMapper.insert(announcementSend);
            });
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAnnouncement(Announcement entity) {
        final Long announcementId = entity.getId();
        boolean result = super.updateById(entity);
        if (result) {
            entity = super.getById(entity.getId());
        }
        if (result && entity.getMsgReceiverUserType().equals(MessageConstant.MSG_RECEIVER_USER_TYPE_USER) && StrUtil.isNotBlank(entity.getUserIds())) {
            LambdaQueryWrapper<AnnouncementSend> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AnnouncementSend::getAnnouncementId, announcementId);
            List<AnnouncementSend> oldList = announcementSendMapper.selectList(queryWrapper);

            List<String> oldIds = oldList.stream().map(AnnouncementSend::getUserId).collect(Collectors.toList());
            Map<String, Long> oldMap = oldList.stream().collect(Collectors.toMap(AnnouncementSend::getUserId, AnnouncementSend::getId));

            List<String> newIds = StrUtil.split(entity.getUserIds(), ",");
            /* 新旧集合相同 */
            if (CollUtil.isEqualList(oldIds, newIds)) {
                return true;
            }
            List<String> intersectionIdList = (List<String>) CollUtil.intersection(oldIds, newIds);
            HashSet<String> intersectionIds = new HashSet<>(intersectionIdList);

            //已经移除数据
            List<String> removeList = new ArrayList<>(oldIds);
            removeList.removeAll(intersectionIds);
            if (!removeList.isEmpty()) {
                for (String removeId : removeList) {
                    announcementSendMapper.deleteById(oldMap.get(removeId));
                }
            }
            //新增数据
            List<String> saveIdList = new ArrayList<>(newIds);
            saveIdList.removeAll(intersectionIds);
            Date refDate = new Date();
            for (String userId : saveIdList) {
                AnnouncementSend announcementSend = new AnnouncementSend();
                announcementSend.setAnnouncementId(announcementId);
                announcementSend.setUserId(userId);
                announcementSend.setReadFlag(MessageConstant.NO_READ_FLAG);
                announcementSend.setReadTime(refDate);
                announcementSendMapper.insert(announcementSend);
            }
        }
        return result;
    }

    @Override
    public IPage<AnnouncementMessageResult> customSelectPage(Page<Announcement> page, AnnouncementQuery query, QueryWrapper<Announcement> queryWrapper) {
        return baseMapper.customSelectPage(page, query,queryWrapper);
    }

}
